<template>
  <div class="user-list">
    <div class="page-header">
      <h1>用户管理</h1>
      <p>管理系统中的所有用户</p>
    </div>

    <el-card>
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="用户名">
            <el-input
              v-model="searchForm.username"
              placeholder="请输入用户名"
              clearable
              style="width: 200px"
              @keyup.enter="loadUsers"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="正常" value="0" />
              <el-option label="停用" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadUsers">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="table-header">
        <h3>用户列表</h3>
      </div>
      
      <el-table :data="users" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" :index="getTableIndex" />
        <el-table-column label="用户名" prop="username" />
        <el-table-column label="姓名" prop="realName" />
        <el-table-column label="邮箱" prop="email" />
        <el-table-column label="角色" width="100">
          <template v-slot="{ row }">
            <el-tag :type="row.role === '0' ? 'danger' : 'primary'" size="small">
              {{ row.role === '0' ? '管理员' : '用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template v-slot="{ row }">
            <el-tag :type="row.status === '0' ? 'success' : 'danger'" size="small">
              {{ row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template v-slot="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template v-slot="{ row }">
            <el-button size="small" @click="editUser(row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="row.status === '0' ? 'warning' : 'success'"
              @click="toggleUserStatus(row)"
              :loading="row.statusLoading"
              :disabled="row.role === '0'"
            >
              {{ row.status === '0' ? '停用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="editDialog.visible"
      title="编辑用户"
      width="500px"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editDialog.form"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editDialog.form.username" disabled />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="editDialog.form.realName" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editDialog.form.email" />
        </el-form-item>
      </el-form>
      
      <template v-slot:footer>
        <el-button @click="editDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="updateUser" :loading="editDialog.loading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const loading = ref(false)
const users = ref([])
const editFormRef = ref()

// 搜索表单
const searchForm = reactive({
  username: '',
  status: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 编辑对话框
const editDialog = reactive({
  visible: false,
  loading: false,
  form: {
    id: null,
    username: '',
    realName: '',
    email: ''
  }
})

// 编辑表单验证规则
const editRules = {
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 获取表格索引
const getTableIndex = (index) => {
  return (pagination.current - 1) * pagination.size + index + 1
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 加载用户数据
const loadUsers = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await request.get('/users/page', { params })
    
    users.value = response.data.records.map(user => ({
      ...user,
      statusLoading: false
    }))
    pagination.total = response.data.total
    
    console.log('加载用户数据成功:', response.data)
  } catch (error) {
    console.error('加载用户数据失败:', error)
    ElMessage.error('加载用户数据失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.username = ''
  searchForm.status = ''
  pagination.current = 1
  loadUsers()
}

// 分页大小改变
const handleSizeChange = (newSize) => {
  pagination.size = newSize
  pagination.current = 1
  loadUsers()
}

// 当前页改变
const handleCurrentChange = (newCurrent) => {
  pagination.current = newCurrent
  loadUsers()
}

// 编辑用户
const editUser = (user) => {
  editDialog.form = {
    id: user.id,
    username: user.username,
    realName: user.realName || '',
    email: user.email || ''
  }
  editDialog.visible = true
}

// 更新用户信息
const updateUser = async () => {
  try {
    if (editFormRef.value) {
      await editFormRef.value.validate()
    }
    
    editDialog.loading = true
    
    await request.put('/users/' + editDialog.form.id, {
      realName: editDialog.form.realName,
      email: editDialog.form.email
    })
    
    ElMessage.success('更新用户信息成功')
    editDialog.visible = false
    loadUsers()
  } catch (error) {
    console.error('更新用户信息失败:', error)
    if (error.name !== 'validationError') {
      ElMessage.error('更新用户信息失败')
    }
  } finally {
    editDialog.loading = false
  }
}

// 重置编辑表单
const resetEditForm = () => {
  editDialog.form = {
    id: null,
    username: '',
    realName: '',
    email: ''
  }
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 切换用户状态
const toggleUserStatus = async (user) => {
  if (user.role === '0') {
    ElMessage.warning('不能停用管理员账户')
    return
  }
  
  const action = user.status === '0' ? '停用' : '启用'
  const newStatus = user.status === '0' ? '1' : '0'
  
      try {
      await ElMessageBox.confirm(
        '确定要' + action + '用户 "' + user.username + '" 吗？',
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      
      user.statusLoading = true
      
      await request.put('/users/' + user.id + '/status', null, {
        params: { status: newStatus }
      })
      
      user.status = newStatus
      user.statusLoading = false
      
      ElMessage.success(action + '成功')
    } catch (error) {
      user.statusLoading = false
      if (error !== 'cancel') {
        console.error('切换用户状态失败:', error)
        ElMessage.error(action + '失败')
      }
    }
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  color: #333;
  margin: 0 0 8px 0;
}

.page-header p {
  color: #666;
  margin: 0;
}

.search-section {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 